package com.cskaoyan.order.mq.promo;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.mall.order.dto.CreateSeckillOrderRequest;
import com.cskaoyan.mall.order.dto.CreateSeckillOrderResponse;
import com.cskaoyan.order.service.OrderPromoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.List;

/**
 * @author LY
 * @since 2022/06/27 22:43
 */
@Component
@Slf4j
public class PromoOrderConsumer {

    @Autowired
    OrderPromoService orderPromoService;

    private DefaultMQPushConsumer consumer;

    @PostConstruct
    public void init(){
        consumer = new DefaultMQPushConsumer("promo_order_consumer");
        consumer.setNamesrvAddr("127.0.0.1:9876");
        try {
            consumer.subscribe("promo_order", "*");
            consumer.setMessageListener(new MessageListenerConcurrently() {
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                    MessageExt message = list.get(0);
                    byte[] body = message.getBody();
                    String requestJson = null;
                    try {
                        requestJson = new String(body, 0, body.length, "utf-8");
                        CreateSeckillOrderRequest request = JSON.parseObject(requestJson, CreateSeckillOrderRequest.class);
                        CreateSeckillOrderResponse response = orderPromoService.createPromoOrder(request);

                        if(OrderRetCode.SUCCESS.getCode().equals(response.getCode())){
                            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                        }
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
            });
            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }
}
